package com.example.chatrecommendation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.chatrecommendation.bean.entity.KnowledgeTag;
import com.example.chatrecommendation.mapper.KnowledgeTagMapper;
import com.example.chatrecommendation.mapper.RadarMapper;
import com.example.chatrecommendation.service.KnowledgeTagService;
import com.example.chatrecommendation.tool.QuestionType;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Jasmine-drs
 * @description 针对表【knowledge_tag(知识点标签)】的数据库操作Service实现
 * @Date 2024-03-07 17:22:50
 */
@Service
public class KnowledgeTagServiceImpl extends ServiceImpl<KnowledgeTagMapper, KnowledgeTag> implements KnowledgeTagService {

	private final KnowledgeTagMapper knowledgeTagMapper;
	private final RadarMapper radarMapper;

	public KnowledgeTagServiceImpl(KnowledgeTagMapper knowledgeTagMapper, RadarMapper radarMapper) {
		this.knowledgeTagMapper = knowledgeTagMapper;
		this.radarMapper = radarMapper;
	}

	@Override
	public void getKnowledgeName(HashMap<Integer, String> map, Integer studentId) {
		// 构建查询条件
		LambdaQueryWrapper<KnowledgeTag> tagWrapper = new LambdaQueryWrapper<>();
// 为每对 questionId 和 type 添加一个查询条件
		map.forEach((questionId, type) -> tagWrapper.or(wrapper -> wrapper
				.eq(KnowledgeTag::getValueId, questionId)
				.eq(KnowledgeTag::getType, type)
		));
		tagWrapper.select(KnowledgeTag::getName, KnowledgeTag::getValueId, KnowledgeTag::getType);

// 执行查询操作
		List<KnowledgeTag> knowledgeTags = knowledgeTagMapper.selectList(tagWrapper);
		System.out.println("knowledgeTags = " + knowledgeTags);
// 将查询结果处理为映射，方便后续处理
		Map<Pair<Integer, Integer>, List<String>> tagMap = knowledgeTags.stream()
				.collect(Collectors.groupingBy(
						tag -> Pair.of(tag.getValueId(), tag.getType()),
						Collectors.mapping(tag -> QuestionType.toEnglish(tag.getName()), Collectors.toList())
				));

// 计算每个英文名称出现的次数，键是英文名称，值是次数
		Map<String, Integer> occurrences = tagMap.values().stream()
				.flatMap(Collection::stream) // 将所有英文名称扁平化为一个流
				.collect(Collectors.toMap(Function.identity(), name -> 1, Integer::sum));
		System.out.println("occurrences = " + occurrences);

		Map<String, Object> params = new HashMap<>();
		params.put("occurrences", occurrences); // 这里的 occurrences 是之前计算出来的 Map
		params.put("studentId", studentId); // 这里的 studentId 是要更新的学生 ID

		radarMapper.updateRadar(params);
	}
}




